package com.ruitu.mall_98_2.mine;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.KeyboardUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.RegexUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.view.AddressPickerView;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.mvp.contract.AddAddressContract;
import com.ruitu.mall_98_2.mvp.model.AddAddressModel;
import com.ruitu.mall_98_2.mvp.presenter.AddAddressPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.mine.Address;

public class AddAddressActivity extends MyBaseActivity<AddAddressPresenter, AddAddressModel> implements AddAddressContract.View, AddressPickerView.OnAddressPickerSureListener {
    private LinearLayout ll_select_cantacts;
    private RelativeLayout rl_on_address;
    private TextView tv_address;
    private EditText et_phone, et_name, et_address_detail, et_post_code;
    private Button btn_save;
    private CheckBox cb_status;
    private AddressPickerView addressPickerView;

    private PopupWindow popupWindow;
    private String province, city, county;
    private String status = "0";
    private Address address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        address = (Address) getIntent().getSerializableExtra("address");
        if (address != null) {
            setHeadTitle("编辑收货地址");
            province = address.getProvince();
            city = address.getCity();
            county = address.getCounty();
        } else {
            setHeadTitle("新增收货地址");
        }
        ll_select_cantacts = findViewById(R.id.ll_select_cantacts);
        rl_on_address = findViewById(R.id.rl_on_address);
        et_name = findViewById(R.id.et_name);
        tv_address = findViewById(R.id.tv_address);
        et_phone = findViewById(R.id.et_phone);
        et_address_detail = findViewById(R.id.et_address_detail);
        et_post_code = findViewById(R.id.et_post_code);
        btn_save = findViewById(R.id.btn_save);
        cb_status = findViewById(R.id.cb_status);
//        addressPickerView = findViewById(R.id.addressPickerView);

        setListener();
        if (address != null) {
            et_name.setText(address.getName());
            et_phone.setText(address.getPhone());
            et_post_code.setText(address.getPostalCode());
            tv_address.setText(address.getProvince() + address.getCity() + address.getCounty());
            et_address_detail.setText(address.getAddress());
            if (address.getStatus().equals("1")) {
                cb_status.setChecked(true);
            } else {
                cb_status.setChecked(false);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == ll_select_cantacts) {
            Uri uri = Uri.parse("content://contacts/people");
            Intent intent = new Intent(Intent.ACTION_PICK, uri);
            startActivityForResult(intent, 979);
        }
        if (v == rl_on_address) {
            KeyboardUtils.hideSoftInput(AddAddressActivity.this);
            initPopuWindow();
        }

        if (v == btn_save) {
            String name = et_name.getText().toString();
            String phone = et_phone.getText().toString();
            String addresss = et_address_detail.getText().toString();
            String postCode = et_post_code.getText().toString();
            if (address != null) {
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(addresss) && !TextUtils.isEmpty(county)) {
                    if (RegexUtils.isMobileSimple(phone)) {
                        showProgress();
                        mPresenter.updateAddress(address.getId(), name, province, city, county, addresss, postCode, phone, status);
                    } else {
                        ToastUtils.showShort("请填写正确的手机号");
                    }
                } else {
                    ToastUtils.showShort("请填写完整的地址");
                }
            } else {
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone) && !TextUtils.isEmpty(addresss) && !TextUtils.isEmpty(county)) {
                    if (RegexUtils.isMobileSimple(phone)) {
                        showProgress();
                        mPresenter.addAddress(AppHolder.instance().getUser().getAccountId(), name, province, city, county, addresss, postCode, phone, status);
                    }else {
                        ToastUtils.showShort("请填写正确的手机号");
                    }
                } else {
                    ToastUtils.showShort("请填写完整的地址");
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 979) {
            if (data != null) {
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
                et_name.setText(contacts[0]);
                et_phone.setText(contacts[1].replace(" ", ""));
            }
        }
    }

    private void setListener() {
        ll_select_cantacts.setOnClickListener(this);
        rl_on_address.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        cb_status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    status = "1";
                } else {
                    status = "0";
                }
            }
        });
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_add_address;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            Logg.i(phone.toString());
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Override
    public void onSureClick(String address, String province, String city, String district) {
        this.province = province;
        this.city = city;
        this.county = district;
        tv_address.setText(address);
        popupWindow.dismiss();
    }

    @Override
    public void OnClick(View view) {
        int i = view.getId();
        if (i == R.id.iv_close) {
            popupWindow.dismiss();

        }
    }

    private void initPopuWindow() {
        //初始化PopupWindow自定义布局
        View view = getLayoutInflater().inflate(R.layout.popupwindow_addess_picker_view, null);
        //设置PopupWindow的布局的大小
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setContentView(view);
        addressPickerView = view.findViewById(R.id.addressPickerView);
        addressPickerView.setOnAddressPickerSure(this);
        //设置背景半透明色
        backgroundAlpha(0.5f);
        //popupWindow  事件监听
        popupWindow.setOnDismissListener(new PopupDismissListener());

        View rootView = LayoutInflater.from(AddAddressActivity.this).inflate(R.layout.activity_add_address, null);
        //将PopupWindow置于activity的底部
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void svaeSuccess() {
        Arad.bus.post(new EventModel(18061100));
        finish();
    }

    class PopupDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    private void backgroundAlpha(float v) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = v;
        getWindow().setAttributes(layoutParams);
    }

}
